package com.example.demo.service;

import com.example.demo.model.Question;
import com.example.demo.repository.QuestionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * MongoDB服务类，提供对Question实体的存储和检索功能
 */
@Service
public class MongoDBService {
    private static final Logger logger = LoggerFactory.getLogger(MongoDBService.class);

    private final QuestionRepository questionRepository;

    @Autowired
    public MongoDBService(QuestionRepository questionRepository) {
        this.questionRepository = questionRepository;
    }

    /**
     * 保存问题到MongoDB
     * @param question 要保存的问题
     * @return 保存后的问题（包含生成的ID）
     */
    public Question saveQuestion(Question question) {
        try {
            Question savedQuestion = questionRepository.save(question);
            logger.info("Question saved successfully with ID: {}", savedQuestion.getId());
            return savedQuestion;
        } catch (Exception e) {
            logger.error("Error saving question to MongoDB", e);
            return null;
        }
    }

    /**
     * 根据ID查找问题
     * @param id 问题ID
     * @return 包含问题的Optional对象
     */
    public Optional<Question> findQuestionById(String id) {
        try {
            return questionRepository.findById(id);
        } catch (Exception e) {
            logger.error("Error finding question by ID: {}", id, e);
            return Optional.empty();
        }
    }

    /**
     * 根据用户ID查找该用户的所有问题
     * @param userId 用户ID
     * @return 问题列表
     */
    public List<Question> findQuestionsByUserId(Long userId) {
        try {
            return questionRepository.findByUserId(userId);
        } catch (Exception e) {
            logger.error("Error finding questions for user ID: {}", userId, e);
            return Collections.emptyList();
        }
    }

    /**
     * 根据用户名查找该用户的所有问题
     * @param username 用户名
     * @return 问题列表
     */
    public List<Question> findQuestionsByUsername(String username) {
        try {
            return questionRepository.findByUsername(username);
        } catch (Exception e) {
            logger.error("Error finding questions for username: {}", username, e);
            return Collections.emptyList();
        }
    }

    /**
     * 根据关键词搜索问题
     * @param keyword 关键词
     * @return 包含关键词的问题列表
     */
    public List<Question> searchQuestionsByKeyword(String keyword) {
        try {
            return questionRepository.findByQuestionTextContaining(keyword);
        } catch (Exception e) {
            logger.error("Error searching questions with keyword: {}", keyword, e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取所有问题
     * @return 所有问题的列表
     */
    public List<Question> findAllQuestions() {
        try {
            return questionRepository.findAll();
        } catch (Exception e) {
            logger.error("Error finding all questions", e);
            return Collections.emptyList();
        }
    }

    /**
     * 分页获取问题
     * @param pageable 分页参数
     * @return 分页的问题结果
     */
    public Page<Question> findQuestionsWithPagination(Pageable pageable) {
        try {
            return questionRepository.findAll(pageable);
        } catch (Exception e) {
            logger.error("Error finding questions with pagination", e);
            throw new RuntimeException("Failed to retrieve paginated questions", e);
        }
    }

    /**
     * 删除问题
     * @param id 要删除的问题ID
     */
    public void deleteQuestion(String id) {
        try {
            questionRepository.deleteById(id);
            logger.info("Question deleted successfully with ID: {}", id);
        } catch (Exception e) {
            logger.error("Error deleting question with ID: {}", id, e);
        }
    }

    /**
     * 根据用户名和问题文本关键词查询问题，按创建时间倒序排列
     * @param username 用户名（可选，为null时查询所有用户）
     * @param questionText 问题文本关键词（可选，为null时查询所有问题）
     * @return 按创建时间倒序排列的问题列表
     */
    public List<Question> findQuestionsByUsernameAndKeywordOrderByCreatedAtDesc(String username, String questionText) {
        try {
            if (username != null && questionText != null) {
                // 同时指定用户名和关键词
                return questionRepository.findByUsernameAndQuestionTextContainingOrderByCreatedAtDesc(username, questionText);
            } else if (username != null) {
                // 只指定用户名
                return questionRepository.findByUsernameOrderByCreatedAtDesc(username);
            } else if (questionText != null) {
                // 只指定关键词
                return questionRepository.findByQuestionTextContainingOrderByCreatedAtDesc(questionText);
            } else {
                // 都不指定，查询所有问题
                return questionRepository.findAllByOrderByCreatedAtDesc();
            }
        } catch (Exception e) {
            logger.error("Error finding questions by username: {} and keyword: {}", username, questionText, e);
            return Collections.emptyList();
        }
    }

    /**
     * 分页查询问题，支持按用户名和问题文本关键词查询，按创建时间倒序排列
     * @param username 用户名（可选，为null时查询所有用户）
     * @param questionText 问题文本关键词（可选，为null时查询所有问题）
     * @param pageable 分页参数
     * @return 分页的问题结果
     */
    public Page<Question> findQuestionsByUsernameAndKeywordOrderByCreatedAtDescWithPagination(String username, String questionText, Pageable pageable) {
        try {
            if (username != null && questionText != null) {
                // 同时指定用户名和关键词
                return questionRepository.findByUsernameAndQuestionTextContainingOrderByCreatedAtDesc(username, questionText, pageable);
            } else if (username != null) {
                // 只指定用户名
                return questionRepository.findByUsernameOrderByCreatedAtDesc(username, pageable);
            } else if (questionText != null) {
                // 只指定关键词
                return questionRepository.findByQuestionTextContainingOrderByCreatedAtDesc(questionText, pageable);
            } else {
                // 都不指定，查询所有问题
                return questionRepository.findAllByOrderByCreatedAtDesc(pageable);
            }
        } catch (Exception e) {
            logger.error("Error finding questions by username: {} and keyword: {} with pagination", username, questionText, e);
            throw new RuntimeException("Failed to retrieve paginated questions", e);
        }
    }
}
